﻿using UnityEngine;
using System.Collections;
using BestHTTP;
using System;
using System.Text;

public class AudioNetworkHandler : MonoBehaviour
{
    public string apiUrl = "https://ilab.chu-jiao.com:8069/Interface/speech";
    public Action<string> OnRequestError;
    public Action<SpeechResponse> OnRequestSuccess;

    // 发送byte[]数据的方法
    public IEnumerator SendAudioBytes(byte[] audioData)
    {
        // 打印请求URL
        Debug.Log($"请求URL: {apiUrl}");

        // 打印请求信息
        Debug.Log($"请求参数:");
        Debug.Log($"- 音频数据大小: {audioData.Length} 字节");
        Debug.Log($"- 音频格式: wav");
        Debug.Log($"- 采样率: 16000");

        // 打印音频数据的前32个字节（用于调试）
        StringBuilder audioHex = new StringBuilder();
        audioHex.AppendLine("音频数据前32字节:");
        for (int i = 0; i < Math.Min(32, audioData.Length); i++)
        {
            audioHex.Append($"{audioData[i]:X2} ");
            if ((i + 1) % 16 == 0) audioHex.AppendLine();
        }
        Debug.Log(audioHex.ToString());

        // 创建请求
        var request = new HTTPRequest(new Uri(apiUrl), HTTPMethods.Post, (req, res) =>
        {
            if (res == null || !res.IsSuccess)
            {
                Debug.LogError($"错误: {res?.Message}");
                OnRequestError?.Invoke(res?.Message ?? "请求失败");
                return;
            }

            try
            {
                var response = JsonUtility.FromJson<SpeechResponse>(res.DataAsText);
                OnRequestSuccess?.Invoke(response);
            }
            catch (Exception e)
            {
                Debug.LogError($"解析失败: {e.Message}");
                OnRequestError?.Invoke("解析失败");
            }
        });

        // 添加音频数据
        request.AddBinaryData("file", audioData, "file.wav");
        request.AddField("rate", "16000");
        request.AddField("format", "pcm");

        // 发送请求
        Debug.Log("开始上传...");
        request.Send();

        // 等待请求完成
        while (request.State != HTTPRequestStates.Finished &&
               request.State != HTTPRequestStates.Error &&
               request.State != HTTPRequestStates.Aborted)
        {
            yield return null;
        }

        // 检查请求状态
        if (request.State == HTTPRequestStates.Error)
        {
            Debug.LogError($"请求错误: {request.Exception}");
            OnRequestError?.Invoke("网络请求失败");
        }
        else if (request.State == HTTPRequestStates.Aborted)
        {
            Debug.LogError("请求被中止");
            OnRequestError?.Invoke("请求被中止");
        }
    }

    private byte[] ConvertToByteArray(float[] samples)
    {
        var samplesShort = new short[samples.Length];
        for (var i = 0; i < samples.Length; i++)
        {
            samplesShort[i] = (short)(samples[i] * short.MaxValue);
        }
        
        var bytes = new byte[samplesShort.Length * 2];
        Buffer.BlockCopy(samplesShort, 0, bytes, 0, bytes.Length);
        return bytes;
    }
}
